import { isArray } from 'lodash';
import { reactive, toRaw } from 'vue';
// 分页钩子函数
interface Options {
    page?: number;
    limit?: number;
    fetchFun: (_arg: any) => Promise<any>;
    params?: Record<any, any>;
}
export function usePaging(options: Options) {
    //params reactive创建
    const { page = 0, limit = 10, fetchFun, params = {} } = options;
    // 记录分页初始参数
    const paramsInit = Object.assign({}, toRaw(params));
    // 分页数据
    const pager = reactive({
        page,
        limit,
        total: 0,
        lists: [] as any[],
        loading: 'loading' //nomore  loading  loadmore
    });
    // 请求分页接口
    const getLists = () => {
        if (pager.loading == 'nomore') return;
        console.log('userPaging:::params', params);
        return fetchFun({
            page: pager.page,
            limit: pager.limit,
            ...params
        })
            .then((res: any) => {
                if (isArray(res.data)) {
                    //第一种返回格式
                    pager.lists = pager.lists.concat(res.data);
                    if (res.data.length == 0 || res.data.length < pager.limit) return (pager.loading = 'nomore');
                } else {
                    //第二种返回格式
                    pager.total = res.data.total;
                    pager.lists = pager.lists.concat(res.data.data);
                    if (pager.lists.length >= pager.total) pager.loading = 'nomore';
                }

                return Promise.resolve(res);
            })
            .catch((err: any) => {
                return Promise.reject(err);
            })
            .finally(() => {});
    };
    // 重置为第一页
    const resetPage = () => {
        pager.page = 0;
        pager.loading = 'loading';
        pager.lists = [];
        getLists();
    };
    // 重置参数
    const resetParams = () => {
        Object.keys(paramsInit).forEach((item) => {
            params[item] = paramsInit[item];
        });
    };
    return {
        pager,
        getLists,
        resetParams,
        resetPage
    };
}
